package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * @author zsk
 * @create 2022-02-14-9:42
 */
@RestController
public class EmployeeController {

    //依赖注入
    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private HttpSession session;

    /*
    登录查询
    Request URL: http://localhost:8080/employee/login
    Request Method: POST
     */
    @PostMapping("/employee/login")
    public ResultInfo login(@RequestBody Map<String,String> map){
        //接受请求参数
        String username = map.get("username");
        String password = map.get("password");

        //调用service层查询
        ResultInfo resultInfo = employeeService.login(username,password);

        //如果登录成功，往session里保存数据
        if (resultInfo.getCode() == 1){
            //存储数据都在data里
            Employee employee =(Employee)resultInfo.getData();
            session.setAttribute("SESSION_EMPLOYEE", employee);
        }

        //返回结果
        return resultInfo;

    }


    /*
    退出操作
    Request URL: http://localhost:8080/employee/logout
    Request Method: POST
     */
    @PostMapping("/employee/logout")
    public ResultInfo logout(){

        //删除session里存储的数据
        session.invalidate();

        //返回成功标识
        return ResultInfo.success(null);
    }

    /*
    Request URL: http://localhost:8080/employee/find
    Request Method: GET
     */
    @GetMapping("/employee/find")
    public ResultInfo findList(String name){
        //调用service查询,根据姓名查询
        List<Employee> employeeList = employeeService.findByName(name);

        //返回数据
        return ResultInfo.success(employeeList);

    }


    /*
    添加数据
    Request URL: http://localhost:8080/employee
    Request Method: POST
     */
    @PostMapping("/employee")
    public ResultInfo save(@RequestBody Employee employee){
        //调用service层保存
        employeeService.save(employee);

        //返回结果
        return ResultInfo.success(null);

    }

    /*
    回显数据
    Request URL: http://localhost:8080/employee/1492418905178771500
    Request Method: GET
     */
    @GetMapping("/employee/{id}")
    public ResultInfo findById(@PathVariable("id") Long id){

        //调用service查询
        Employee employee = employeeService.findById(id);

        //返回结果
        return ResultInfo.success(employee);
    }

    /*
    修改数据
    Request URL: http://localhost:8080/employee
    Request Method: PUT
     */
    @PutMapping("/employee")
    public ResultInfo update(@RequestBody Employee employee){

        //调用service层修改
        employeeService.update(employee);

        //返回结果
        return ResultInfo.success(null);

    }

}
